import { ref, computed } from 'vue'
import { useQuestionStore } from '@/stores/question'
import type { Question } from '@/types'

export function useQuestions() {
  const questionStore = useQuestionStore()
  
  // 响应式数据
  const questions = ref<Question[]>([])
  const loading = ref(false)
  const error = ref('')
  const currentPage = ref(1)
  const pageSize = ref(10)
  
  // 搜索筛选数据
  const searchFilters = ref({
    search: '',
    difficulty: '',
    tag: '',
    status: '',
    favorite: false
  })
  
  // 计算属性
  const filteredQuestions = computed(() => {
    if (!questions.value) return []
    if (searchFilters.value.favorite) {
      return questions.value.filter(q => q.is_favorited)
    }
    return questions.value
  })
  
  const totalQuestions = computed(() => questionStore.pagination?.total || 0)
  const totalPages = computed(() => questionStore.pagination?.total_pages || 0)
  
  const visiblePages = computed(() => {
    const pages = []
    const maxVisible = 5
    let start = Math.max(1, currentPage.value - Math.floor(maxVisible / 2))
    const end = Math.min(totalPages.value, start + maxVisible - 1)
    
    start = Math.max(1, end - maxVisible + 1)
    
    for (let i = start; i <= end; i++) {
      pages.push(i)
    }
    
    return pages
  })
  
  // 方法
  const loadQuestions = async () => {
    try {
      loading.value = true
      error.value = ''
      
      const success = await questionStore.fetchQuestions({
        page: currentPage.value,
        page_size: pageSize.value,
        difficulty: searchFilters.value.difficulty ? [searchFilters.value.difficulty] : [],
        tags: searchFilters.value.tag ? [searchFilters.value.tag] : [],
        status: searchFilters.value.status ? [searchFilters.value.status] : [],
        search: searchFilters.value.search
      })
      
      if (success) {
        questions.value = questionStore.questions || []
      } else {
        error.value = '获取题目失败，请稍后重试'
      }
    } catch (err) {
      console.error('获取题目失败:', err)
      error.value = '网络错误，请检查网络连接'
    } finally {
      loading.value = false
    }
  }
  
  const handleSearch = () => {
    currentPage.value = 1
    loadQuestions()
  }
  
  const handleFilter = () => {
    currentPage.value = 1
    loadQuestions()
  }
  
  const goToPage = (page: number) => {
    if (page >= 1 && page <= totalPages.value) {
      currentPage.value = page
      loadQuestions()
      window.scrollTo({ top: 0, behavior: 'smooth' })
    }
  }
  
  const toggleFavorite = async (questionId: number) => {
    const question = questions.value?.find(q => q.id === questionId)
    if (!question) return
    
    try {
      if (question.is_favorited) {
        await questionStore.unfavoriteQuestion(questionId)
        question.is_favorited = false
      } else {
        await questionStore.favoriteQuestion(questionId)
        question.is_favorited = true
      }
    } catch (error) {
      console.error('收藏操作失败:', error)
    }
  }
  
  const goToRandomQuestion = async () => {
    if (!questions.value || questions.value.length === 0) {
      await loadQuestions()
    }
    const list = questions.value
    if (list && list.length) {
      const random = list[Math.floor(Math.random() * list.length)]
      return random
    }
    return null
  }
  
  return {
    // 状态
    questions,
    loading,
    error,
    currentPage,
    pageSize,
    searchFilters,
    
    // 计算属性
    filteredQuestions,
    totalQuestions,
    totalPages,
    visiblePages,
    
    // 方法
    loadQuestions,
    handleSearch,
    handleFilter,
    goToPage,
    toggleFavorite,
    goToRandomQuestion
  }
}
